package common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by dpeng on 2015/9/8.
 */
public class MD5 {

	private static final char[] strHex = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};


	public static String createSign(String content) {

		if(null == content || "".equals(content.trim())) {
			throw new IllegalArgumentException("签名参数不能为空");
		}
		return encrypt(content,"MD5");
	}

	//创建签名, charset指定加密模式 如MD5
	public static String createSign(String content, String charset) {

		if(null == content || "".equals(content.trim())) {
			throw new IllegalArgumentException("签名参数不能为空");
		}
		return encrypt(content,charset);
	}

	/**
	 * 验签
	 * @param content  原始串
	 * @param msg  密文
	 * @return
	 */
	public static boolean checkSign(String content,String msg) {
		if(null == msg) {
			throw new IllegalArgumentException("密文不能为空");
		}
		return msg.equals(encrypt(content,"MD5"));
	}

	public static boolean checkSign(String content,String msg,String charset) {
		if(null == msg) {
			throw new IllegalArgumentException("密文不能为空");
		}
		return msg.equals(encrypt(content,charset));
	}

	//加密
	private static String encrypt(String content, String charset) {
		StringBuffer strb = new StringBuffer();
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(charset);
			messageDigest.update(content.getBytes());
			byte[] buf = messageDigest.digest();
			for(int i = 0; i < buf.length; i++) {
				// 将密文简单做个16进制转换
				strb.append(toHex(buf[i] & 0xff));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return strb.toString().toUpperCase();
	}

	public static String toHex(int b) {
		// 凑到32位
		return String.valueOf(strHex[b/16]) + String.valueOf(strHex[b%16]);
	}

}